package com.uziot.bucket.tasklock.task;

import com.uziot.bucket.tasklock.dao.TaskLock;
import com.uziot.bucket.tasklock.dao.TaskLog;
import com.uziot.bucket.tasklock.service.TaskLockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 功能描述: <br>
 * Scheduler1Task
 *
 * @author shidt
 * @date 2019-11-07 16:19
 */
@Slf4j
@Component
public class Scheduler1Task {

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss");
    @Autowired
    private TaskLockService taskLockService;


    @Scheduled(cron = "0/1 * * * * ? ")
    public void report() {
        String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
        TaskLock taskLock = taskLockService.createTaskLock(methodName);
        boolean lock = taskLockService.tryLock(taskLock);
        //获得全局锁
        if (lock) {
            TaskLog taskLog = taskLockService.createTaskLog(methodName);
            try {
                //记录定时任务日志表
                taskLockService.saveTaskLog(taskLog);

                // 执行定时任务
                Thread.sleep(5000);
                System.out.println("定时任务正在执行1，现在时间：" + DATE_FORMAT.format(new Date()));

                taskLog.setResult("normal");
            } catch (Exception e) {
                log.error("定时任务执行发生异常！{}", e.toString());
                taskLog.setResult("error");
            } finally {
                //修改定时任务日志表
                taskLockService.updateTaskLog(taskLog);
                //释放全局锁
                taskLockService.removeTaskLock(taskLock);
            }
        }
    }


}
